#include <stdint.h>
#include <stdio.h>

#include "src/lta.h"
#include "src/ltbase.h"
#include "src/lterr.h"
#include "src/ltini.h"
#include "src/ltlog.h"
#include "src/ltopt.h"

static int
TestVisitor(void* ctx, int line_num, char const* section, char const* key,
            char const* value) {
    (void)ctx;
    ltlog_Log4(Info, "visit ini", "line:", U32(line_num),
               "section:", StringQuote(section), "key:", StringQuote(key),
               "value:", StringQuote(value));
    return 0;
}

static void
ShowINI(FILE* fp) {
    lterr_Code code = ltini_Parse(fp, ltio_FilePtrReadChar, NULL, TestVisitor);

    ltlog_Log1(Info, "parse done", "result:", String(lterr_Name(code)));
}

static lterr_Code
OnArgument(void* ctx, char name, char const* value) {
    lta_Strings* files = (lta_Strings*)ctx;

    switch (name) {
        case 0: lta_Append(*files, value); break;
        default: return lterr_kError;
    }

    return lterr_kOk;
}

int
ini_show_Run(int argc, char const* argv[]) {
    lta_Strings files = {0};

    lterr_Code r = ltopt_Parse(argc, argv, "", OnArgument, &files);
    if (r != 0) {
        ltlog_Log1(Error, "failed to parse command line",
                   "error:", String(lterr_Name(r)));
        return 1;
    }

    if (files.len == 0) {
        ltlog_Log0(Error, "missing input file");
        return 0;
    }

    for (lt_USize i = 0; i < files.len; ++i) {
        FILE* fp = fopen(files.data[i], "r");
        ShowINI(fp);
        fclose(fp);
    }

    return 0;
}
